package com.wxit.algorithm.leetcode;

/**
 * 合并两个有序链表
 */
public class E06LeetCode21 {

    /**
     * 指针的思想
     * @param p1
     * @param p2
     * @return
     */
    public ListNode mergeTwoLists01(ListNode p1, ListNode p2) {
        ListNode s = new ListNode(-1, null);
        ListNode p = s;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                //p1向后移动, p链接给p1
                p.next = p1;
                p1 = p1.next;
            } else {
                //p2向后移动, p链接给p2
                p.next = p2;
                p2 = p2.next;
            }
            p = p.next;
        }
        if (p1 != null) {
            p.next = p1;
        }
        if (p2 != null) {
            p.next = p2;
        }
        return s.next;
    }

    /**
     * 方法二： 递归实现
     * @param p1
     * @param p2
     * @return
     */
    public ListNode mergeTwoLists(ListNode p1, ListNode p2) {
        //终止条件
        if (p2 == null) {
            return p1;
        }
        if (p1 == null) {
            return p2;
        }
        if (p1.val < p2.val) {
            p1.next = mergeTwoLists(p1.next, p2);
            return p1;
        } else {
            p2.next = mergeTwoLists01(p1, p2.next);
            return p2;
        }
    }

    public static void main(String[] args) {
        ListNode head1 = ListNode.of(1, 2, 4);
        ListNode head2 = ListNode.of(1, 3, 4);
        System.out.println(new E06LeetCode21().mergeTwoLists(head1, head2));
    }
}
